import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "@/views/Login.vue"
import Home from "@/views/Home.vue"
import ElementUI from 'element-ui'
import Register from '@/views/Register'
import My from '@/views/My.vue'
import Myorder from'@/views/Myorder.vue'
import User from '@/views/User.vue'
import Car from '@/views/Car.vue'
import Admin from '@/views/Admin.vue'
import News from '@/views/News.vue'

Vue.use(ElementUI)
Vue.use(VueRouter)



const routes = [
  {
    path:'/news',
    name:'news',
    component:News
  },
  {
    path:'/my',
    name:'my',
    component:My
  },
  {
    path:'/admin',
    name:'admin',
    component:Admin
  },
  {
    path:'/car',
    name:'car',
    component:Car
  },
  {
    path:'/user',
    name:'user',
    component:User
  },
  {
    path:'/myorder',
    name:'myorder',
    component:Myorder
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },

 
  {
    path: '/register',
    name: 'register',
    component: Register
  },

  {
    path: '/',
    name: 'login',
    component: Login
  }
  
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {
  // 1.如果访问的是登录页面（无需权限），直接放行
  if (to.path === '/' || to.path === '/Register') return next()
  // 2.如果访问的是有登录权限的页面，先要获取token
  const tokenStr = JSON.parse(localStorage.getItem('user'))
  // 2.1如果token为空，强制跳转到登录页面；否则，直接放行
  if (!tokenStr) {
    alert("请登录")
    return next({
      path:('/')
    })
  }
  next()
})

export default router
